package com.ccys.common.third.gap;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ccys.common.enums.CodeEnum;
import com.ccys.common.util.JedisUtil;
import com.ccys.common.util.RestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ccys.common.constants.Constants.COUNTRY_INDONESIA_ID;
import static com.ccys.common.constants.Constants.COUNTRY_SINGAPORE_ID;

/**
 * @ClassName: GapUtil
 * @Description:
 * @Author: billyhu
 * @Date: 2024/2/26 20:13
 */
@Slf4j
public class GapUtil {


    public static final String INDONESIA_WAIVED_CONSULTATION_PRODUCT_MASTER_ID = "901330";

    public static final String INDONESIA_OFFICE_HOURS_PRODUCT_MASTER_ID = "716344";

    public static final String INDONESIA_AFTER_HOURS_PRODUCT_MASTER_ID = "706187";

    public static final String SINGAPORE_OFFICE_HOURS_PRODUCT_MASTER_ID = "716332";

    public static final String SINGAPORE_AFTER_HOURS_PRODUCT_MASTER_ID = "716338";

    public static final String INDONESIA_AIA_PRODUCT_MASTER_ID = "901322";

    public static final String SINGAPORE_AIA_PRODUCT_MASTER_ID = "901323";

    public static final String X_CLIENT_ID = "WHITECOAT";

    public static final String X_CLIENT_KEY = "41138489-1057-4e7e-ab93-9bc97b511cf6";

    public static final String BASE_URL = "https://opendev.goapotik.com/v1/";

    public static Map<String,String> HEADER = new HashMap<>();

    static {
        HEADER.put("X-CLIENT-ID",X_CLIENT_ID);
        HEADER.put("X-CLIENT-KEY",X_CLIENT_KEY);
    }

    /**
     * 获取token
     * 暂不清楚有效期多长，做缓存并定时删除
     * @return
     */
    public static String authToken(){
        String token = JedisUtil.get("gap_token", CodeEnum.REDIS_THIRD.codeOf());
        if(StringUtils.isNotBlank(token)){
            return token;
        }
        String result = RestUtil.executeForm(BASE_URL + "auth/token", HttpMethod.GET, HEADER, null);
        try {
            JSONObject json = JSONObject.parseObject(result);
            token = json.getJSONObject("data").getString("token_value");
            JedisUtil.setex("gap_token",60*30,token, CodeEnum.REDIS_THIRD.codeOf());
            return token;
        }catch (Exception e){
            log.error("获取token异常:",e);
        }
        return null;
    }
    private static void setAuthToken(){
        HEADER.put("Authorization","Bearer "+authToken());
    }

    public static String getFeeId(Integer isSurcharge,String country,Boolean isWaiveConsultFee,Integer isAIAIdentifier){
        String gapId = null;
        if (isWaiveConsultFee) {
            //_waivedConsultationProductMasterId
            gapId = GapUtil.INDONESIA_WAIVED_CONSULTATION_PRODUCT_MASTER_ID;
        } else {
            if (COUNTRY_INDONESIA_ID.equals(country)) {
                //印尼
                if (isAIAIdentifier == 1) {
                    //_aiaIndonesiaProductMasterId
                    gapId = GapUtil.INDONESIA_AIA_PRODUCT_MASTER_ID;
                } else {
                    if (0 == isSurcharge) {
                        //_officeHoursIndonesiaProductMasterId
                        gapId = GapUtil.INDONESIA_OFFICE_HOURS_PRODUCT_MASTER_ID;
                    } else {
                        //_afterHoursIndonesiaProductMasterId
                        gapId = GapUtil.INDONESIA_AFTER_HOURS_PRODUCT_MASTER_ID;
                    }
                }
            } else if (COUNTRY_SINGAPORE_ID.equals(country)) {
                //新加坡
                if (isAIAIdentifier == 1) {
                    //_aiaSingaporeProductMasterId
                    gapId = GapUtil.SINGAPORE_AIA_PRODUCT_MASTER_ID;
                } else {
                    if (0 == isSurcharge) {
                        //_officeHoursSingaporeProductMasterId
                        gapId = GapUtil.SINGAPORE_OFFICE_HOURS_PRODUCT_MASTER_ID;
                    } else {
                        //_afterHoursSingaporeProductMasterId
                        gapId = GapUtil.SINGAPORE_AFTER_HOURS_PRODUCT_MASTER_ID;
                    }
                }
            }
        }
        return gapId;
    }

    /**
     * todo 集成以下方法
     *
     *
     * $"{_host}{_version}/shipping/{customerId}
     * $"{_host}{_version}/checkout/{customerId}";
     * $"{_host}{_version}/paymentlist/{customerId}";
     * $"{_host}{_version}/setpayment/{customerId}";
     * $"{_host}{_version}/order/detail?invoice_no={invoiceId}";
     * $"{_host}{_version}/product/therapeutic/details?product_master_id={productId}";
     * $"{_host}{_version}/prescriptionupload"
     * $"{_host}{_version}/canceltransaction";
     * $"{_host}{_version}/orderlistbystatus/{customerId}?status=pending_payment";
     * $"{_host}{_version}/rollbackcoupon";
     * $"{_host}{_version}/order/updatestatus";
     * @return
     */


    /**
     * $"{_host}{_version}/product/validateproducts";
     * 返回示例:
     * {
     *     "code": "SGP-01-001",
     *     "data": {
     *         "match_products": [
     *             {
     *                 "id": 37892,
     *                 "product_name": "ACANTHE LIGHTENING GEL 10 ML"
     *             },
     *             {
     *                 "id": 716344,
     *                 "product_name": "WHITE COAT COSULTATION - ID DOCTOR OFFICE HOURS"
     *             }
     *         ],
     *         "merchant": {
     *             "id": 28,
     *             "merchant_name": "Merchant Testing Dev"
     *         },
     *         "similar_products": []
     *     },
     *     "message": "Success, Origin Response :  Success"
     * }
     * 医生检查gap药品
     * @return
     */
    public static String doctorValidateProducts(Map<String,Object> param){
        setAuthToken();
        return RestUtil.executeJson(BASE_URL + "product/validateproducts", HttpMethod.POST, HEADER, param);
    }

    /**
     * $"{_host}{_version}/checkout/instant"
     * 结算
     * 请求示例
     * {
     *     "buyer":{
     *         "email": "123@123.123",
     *         "name" : "123",
     *         "phone" : "41343154"
     *     },
     *     "recipient":{
     *         "name" : "123",
     *         "phone" : "41343154",
     *         "address:":{
     *             "address_full":"Jl. M.H. Thamrin No.30, Gondangdia, Kec. Menteng, Kota Jakarta Pusat, Daerah Khusus Ibukota Jakarta 10350 Indonesia",
     *             "latitude": "-6.274098",
     *             "longitude": "106.71",
     *             "postal_code":"12190"
     *         }
     *     },
     *     "products":[
     *         {
     *             "id":34629,
     *             "quantity":2
     *         }
     *     ],
     *     "best_combination":true,
     *     "similarmoleculeproduct":false,
     *     "multi_merchant":false,
     *     "no_range":true,
     *     "order_source":"WHC",
     *     "consultation":{
     *         "product_master_id" : 901330,
     *         "price":123.2
     *     }
     * }
     * 但是没走通，提示
     * {
     *     "code": "EGA-01-001",
     *     "err": "Key: 'CheckoutInstant.Recipient.Address.AddressFull' Error:Field validation for 'AddressFull' failed on the 'required' tag\nKey: 'CheckoutInstant.Recipient.Address.Latitude' Error:Field validation for 'Latitude' failed on the 'required' tag\nKey: 'CheckoutInstant.Recipient.Address.Longitude' Error:Field validation for 'Longitude' failed on the 'required' tag\nKey: 'CheckoutInstant.Recipient.Address.PostalCode' Error:Field validation for 'PostalCode' failed on the 'required' tag",
     *     "message": "Your payload data is invalid"
     * }
     */
    public static String getMerchant(Map<String,Object> param){
        setAuthToken();
        return RestUtil.executeJson(BASE_URL + "checkout/instant", HttpMethod.POST, HEADER, param);
    }

    /**
     * 通过getMerchant获取参数
     * $"{_host}{_version}/shipping/{customerId}?merchant_id={merchantId}&shipping_agency={shippingFilter}"
     * @param customerId
     * @param merchantId
     * @param shippingFilter
     * @return
     */
    public static String getShipping(Integer customerId,Integer merchantId,String shippingFilter){
        setAuthToken();
        return HttpUtil.get(BASE_URL + "shipping/" + customerId + "?merchant_id=" + merchantId + "&shipping_agency=" + shippingFilter);

    }


       /**
        * @description Get Review Receipt
        *  $"{_host}{_version}/checkout/{customerId}";
        * @param customerId
        * @param initial
        * @date     2024/3/7
        * @author   cloud fly
        */

    public static String getCheckoutReview(Integer customerId,Integer initial){
        setAuthToken();
        if(initial == null) {
            return null;
        }
        Map<String,Object> param = new HashMap<>();
        param.put(initial.toString(), initial);
        return RestUtil.executeJson(BASE_URL + "checkout/" + customerId , HttpMethod.POST, HEADER, param);

    }

       /**
        * @description 获取支付方式 GetPaymentMethods
        * $"{_host}{_version}/paymentlist/{customerId}";
        * @date     2024/3/7
        * @author   cloud fly
        */
    public static String getPaymentMethods(String customerId){
        setAuthToken();
        String url = BASE_URL + "paymentlist/" + customerId;
        Map<String,String> param = new HashMap<>();
        return RestUtil.executeForm(url, HttpMethod.GET, HEADER, param);

    }



       /**
        * @description 设置支付方式
        * $"{_host}{_version}/setpayment/{customerId}";
        * @date     2024/3/7
        * @author   cloud fly
        */

    public static String setPaymentMethod(String customerId,String paymentCode,String phone){
        setAuthToken();
        Map<String,Object> param = new HashMap<>();
        param.put("payment_code", paymentCode);
        param.put("phone", phone);
        return RestUtil.executeJson(BASE_URL + "setpayment/" + customerId , HttpMethod.POST, HEADER, param);

    }


    /**
     * Get payment detail on GoApotik
     * $"{_host}{_version}/order/detail?invoice_no={invoiceId}";
     * @param invoiceId
     * @return
     */
    public static String getPaymentDetail(String  invoiceId){
        setAuthToken();
        if(invoiceId == null) {
            return null;
        }
        Map<String,String> param = new HashMap<>();
        param.put("invoice_no",invoiceId.toString());
        String url = BASE_URL +  "order/detail";
        return RestUtil.executeForm(url, HttpMethod.GET, HEADER, param);

    }


       /**
        * @description GetProductDetail
        * $"{_host}{_version}/product/therapeutic/details?product_master_id={productId}";
        * @date     2024/3/7
        * @author   cloud fly
        */
    public static String GetProductDetail(Integer productId){
        setAuthToken();
        if(productId == null) {
            return null;
        }
        Map<String,String> param = new HashMap<>();
        param.put("product_master_id",productId.toString());
        String url = BASE_URL + "product/therapeutic/details";
        String result = RestUtil.executeForm(url, HttpMethod.GET, HEADER, param);
        return result;

    }




       /**
        * @description UploadPrescriptionToGoApotik
        * $"{_host}{_version}/prescriptionupload";
        * @date     2024/3/7
        * @author   cloud fly
        */
    public static String UploadPrescriptionToGoApotik(Integer incrementId,String imageBase64){
        setAuthToken();
        Map<String,Object> param = new HashMap<>();
        param.put("increment_id", incrementId);
        param.put("image", imageBase64);
        String url = BASE_URL + "prescriptionupload";
        return RestUtil.executeJson(url, HttpMethod.POST, HEADER, param);

    }


       /**
        * @description CancelTransaction
        * $"{_host}{_version}/canceltransaction";
        * @date     2024/3/7
        * @author   cloud fly
        */
    public static String cancelTransaction(String incrementId,String customerId,String reason){
        setAuthToken();
        Map<String,Object> param = new HashMap<>();
        param.put("increment_id", incrementId);
        param.put("customer_id", customerId);
        List<JSONObject> reasons = new ArrayList<>();
        JSONObject  reasonJson = new JSONObject();
        reasonJson.put("Reason",reason);
        reasons.add(reasonJson);
        param.put("reasons",reasons);
        String url = BASE_URL + "canceltransaction";
        return RestUtil.executeJson(url, HttpMethod.POST, HEADER, param);

    }

       /**
        * @description GetOrderPendingPayment
        * $"{_host}{_version}/orderlistbystatus/{customerId}?status=pending_payment";
        * @date     2024/3/7
        * @author   cloud fly
        */
    public static String getOrderPendingPayment(String customerId){
        setAuthToken();
        Map<String,String> param = new HashMap<>();
        param.put("status","pending_payment");
        String url = BASE_URL + "orderlistbystatus/" + customerId + "?status=pending_payment";
        String result = RestUtil.executeForm(url, HttpMethod.GET, HEADER, param);
        return result;

    }



       /**
        * @description RollbackCoupon
        * $"{_host}{_version}/rollbackcoupon";
        * @date     2024/3/7
        * @author   cloud fly
        */

    public static String RollbackCoupon(Integer customerId,String code){
        setAuthToken();
        Map<String,Object> param = new HashMap<>();
        param.put("coupon_code", code);
        param.put("customer_id", customerId);
        String url = BASE_URL + "rollbackcoupon";
        return RestUtil.executeJson(url, HttpMethod.POST, HEADER, param);

    }



       /**
        * @description UpdateOrderStatus
        * $"{_host}{_version}/order/updatestatus";
        * @date     2024/3/7
        * @author   cloud fly
        */
    public static String UpdateOrderStatus(Integer customerId,Integer incrementId){
        setAuthToken();
        Map<String,Object> param = new HashMap<>();
        param.put("mask_id", incrementId);
        param.put("customer_id", customerId);
        String url = BASE_URL + "order/updatestatus";
        return RestUtil.executeJson(url, HttpMethod.POST, HEADER, param);

    }



}
